/**
 * 项目公共的编辑器配置(quill)
 */

//本模块的加载配置
require.config({
	baseUrl:'/web/modules/common/we-quill',
	paths: {
		"vue" : "libs/vue2",
		"quill": "libs/quill/quill",
		"vue-quill": "libs/vue-quill-editor",
		"img-resize": "libs/image-resize-require",
	}　　　　
});
		
define(function(require, exports, module) {
	//模块依赖
	var Vue = require('vue'),
	    Quill = require('quill'),
		VueQuillEditor = require('vue-quill');
		imageResize = require('img-resize');
		
	Vue.use(VueQuillEditor) ;
	
	//导出
	return Vue.component('we-quill',{
		mixins: [VueQuillEditor],
		props:{
			//v-model传递的属性名为'value'
			value:{
				type:String
			}
		},
		template:'<div class="we-quill">\
					<quill-editor :value="value"\
								@input="handleInput"\
					            :options="editorOption"\
					            @ready="onEditorReady($event)">\
					</quill-editor>\
				 </div>',
        data : function() {
    	    return {
			    maxWidth:600,
			    
			    //编辑器设置
			    editorOption: {
			    	debug: 'error',
			    	modules: {
			    		//语法高亮
			    		syntax: {
			    			highlight: function(text){
			    				return hljs.highlightAuto(text).value ;
			    			} 
			    		},
			    		//工具栏
			    		toolbar:[
                        	['bold', 'italic', 'link', 'blockquote'],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
	                  		['code-block'],
	                  		[{ 'header': 1 }, { 'header': 2 }],
	                  	 	['image'],
                        ],
	    	            //图片大小调整
	    	            imageResize: {
	    	              displayStyles: {
	    	                backgroundColor: 'black',
	    	                border: 'none',
	    	                color: 'white'
	    	              },
	    	              modules: [ 'Resize', 'DisplaySize']
	    	            }
                    },
			    	placeholder: '请输入内容，不超过1000字...',
			    	//是否可编辑
			    	readOnly: false,
			    	//主题风格
			    	theme: 'snow'
			    }
    	    }
        },
        methods:{
        	handleInput(val) {
        		//通知父组件更新值
        	    this.$emit('input', val);
        	    this.$emit('change', val);
        	},
        	uploadImage:function(formData,quill,width,height){
    		  //加载样式
  	  		  var loadLayer = layer.load(1, {
  	  	  		    shade: [0.5,'#000000'] //0.1透明度的白色背景 
  	  	  	  });
        		var vm = this ;
	    		$.ajax({
	                    url: '/ueditor/uploadImage.html',
	                    type: 'POST',
	                    cache: false,
	                    data: formData,
	                    processData: false,
	                    contentType: false
	                }).success(function(res) {
	                	if(200 == res.status){
	                		var range=quill.getSelection(true);
	                		var imgUrl = 'http://image.sktcm.cn/' + res.data ;
	                		if(width > vm.maxWidth){
	                			imgUrl += ('?imageMogr2/thumbnail/'+vm.maxWidth+'x/format/jpg/q/100!/strip'); 
	                		}else{
	                			imgUrl += ('?imageMogr2/format/jpg/q/100!/strip'); 
	                		}
   	                   	quill.insertEmbed(range.index, 'image',imgUrl);
   	                   	quill.setSelection(range.index+1);
   	                    //关闭遮罩层
   			   		    layer.close(loadLayer) ;
	                	}else{
	                		log('图片上传失败');
	                	}
	                	
	                }).error(function(res) {
	                	log('图片上传失败');
	                });
	    	},
	        onEditorReady(quill){
	    		var vm = this ;
	        	//重写编辑器的图片预览方法
		    	var toolbar = quill.getModule('toolbar'),
		    	fileInput = quill.container.querySelector('input.ql-image[type=file]');
	        	
		    	toolbar.addHandler('image',function(){
                	if (fileInput == null) {
                	    fileInput = document.createElement('input');
                	    fileInput.setAttribute('type', 'file');
               	        fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
               	        fileInput.classList.add('ql-image');
               	        
                	    fileInput.addEventListener('change', function () {
                	    	var file = this.files[0];
               	            if (null != file && undefined != file) {
               	             	var formData = new FormData();
               	                formData.append('image', file);
               	                
               	             	var image = new Image()
               	             	var reader = new FileReader();
               	          		reader.onload = function(e){
               	          			image.src = e.target.result;
               	          			image.onload = function () {
	               	                 	console.log('width:'+image.width+'----height:'+image.height);
	               	                 	vm.uploadImage(formData,quill,image.width,image.height) ;
	               	             	}
               	             	}
               	          		reader.readAsDataURL(file);
               	             }
                	     });
                	     this.container.appendChild(fileInput);
               		}
                	//fileInput not null
                	fileInput.click();
		    	});
	        }
        }
    }) ;
});